package com.vhall.component.plugin.common.utils;

import org.apache.commons.collections.CollectionUtils;

import java.security.SecureRandom;
import java.util.*;

/**
 * @author dalong
 * @description
 * @classname ArrayUtil
 * @date 2021-03-31 10:59
 */
public class ArrayUtil {

    /**
     * 随机获取数组的N个元素
     *
     * @param <T>
     * @param list   数组
     * @param count  获取几个元素
     * @param remove 删除下标元素 0否 1是
     * @return
     */
    public static <T> List<T> randomGetElement(List<T> list, Integer count, boolean remove) {
        List<T> arrayListReturn = new ArrayList<>();
        Set<T> arraySetReturn = new HashSet<>();
        SecureRandom random = new SecureRandom();
        Iterator<T> it = list.iterator();
        while (it.hasNext()) {
            //随机获取一个数据下标
            int randomIdx = random.nextInt(list.size());
            arraySetReturn.add(list.get(randomIdx));
            if (remove) {
                // 删除原数组下标对应数据
                list.remove(randomIdx);
            }
            if (arraySetReturn.size() == count) {
                break;
            }
        }
        arrayListReturn.addAll(arraySetReturn);
        return arrayListReturn;
    }

    /**
     * 分隔数组 根据每段数量分段
     *
     * @param data  被分隔的数组
     * @param count 每段数量
     * @return
     */
    public static <T> List<List<T>> subListByCount(List<T> data, int count) {
        List<List<T>> result = new ArrayList<>();
        int size = data.size();
        if (CollectionUtils.isNotEmpty(data) && count > 0) {
            int segments = size / count;
            // 段数
            segments = size % count == 0 ? segments : segments + 1;
            // 每段List
            List<T> cutList = null;
            for (int i = 0; i < segments; i++) {
                if (i == segments - 1) {
                    cutList = data.subList(count * i, size);
                } else {
                    cutList = data.subList(count * i, count * (i + 1));
                }
                result.add(cutList);
            }
        } else {
            result.add(data);
        }
        return result;
    }

}
